package cn.jeeweb.web.modules.equipment.service.impl;

import cn.jeeweb.common.mybatis.mvc.service.impl.CommonServiceImpl;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.utils.TimeUtils;
import cn.jeeweb.web.modules.equipment.entity.*;
import cn.jeeweb.web.modules.equipment.mapper.EqsMaintenanceTaskMapper;
import cn.jeeweb.web.modules.equipment.service.*;
import cn.jeeweb.web.modules.sys.entity.CodeTable;
import cn.jeeweb.web.modules.sys.service.ICodeTableService;
import cn.jeeweb.web.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description: eqs_maintenance_task服务实现
*/
@Transactional
@Service("eqsMaintenanceTaskService")
public class EqsMaintenanceTaskServiceImpl extends CommonServiceImpl<EqsMaintenanceTaskMapper,EqsMaintenanceTask> implements IEqsMaintenanceTaskService {

    @Autowired
    IEqsMaintenancePlanService eqsMaintenancePlanService;

    @Autowired
    ICodeTableService codeTableService;

    @Autowired
    IEqsMaintenanceCheckService eqsMaintenanceCheckService;

    @Autowired
    IEqsMaintenancePlanCheckTemplateService eqsMaintenancePlanCheckTemplateService;

    @Autowired
    IEqsMaintenanceCheckTemplateService eqsMaintenanceCheckTemplateService;


    @Override
    public boolean createMaintenanceTask(String[] ids,String timeFrame,String sysConfigCode,String json) {
        EntityWrapper<EqsMaintenancePlan> entityWrapper = new EntityWrapper<>(EqsMaintenancePlan.class);
        if(ids != null && ids.length > 0){
            entityWrapper.in("id",ids);
        }
        List<EqsMaintenancePlan> eqsMaintenancePlans = eqsMaintenancePlanService.selectList(entityWrapper);
        List<EqsMaintenanceTask> eqsMaintenanceTasks = new ArrayList<EqsMaintenanceTask>();
        if(eqsMaintenancePlans != null && eqsMaintenancePlans.size() > 0){
            for(EqsMaintenancePlan plan : eqsMaintenancePlans){
                String freqUnit = plan.getFreqUnit();
                String name = plan.getName();
                String code = plan.getCode();
                String planId = plan.getId();
                String equipmentId = plan.getEquipmentId();
                String maintenanceType = plan.getMaintenanceType();
                Date fromDate = plan.getFromDate();
                String userId = UserUtils.getUser().getId();
                EqsMaintenanceTask firstTask = new EqsMaintenanceTask();
                CodeTable codeTable = new CodeTable();
                codeTable.setCode(sysConfigCode);
                firstTask.setCode(codeTableService.createNewCode(codeTable));
                firstTask.setName(name+code);
                firstTask.setPlanId(planId);
                firstTask.setEquipmentId(equipmentId);
                firstTask.setMaintenanceType(maintenanceType);
                firstTask.setTaskDate(fromDate);
//                firstTask.setExecutor(userId);
                if("weekly".equals(freqUnit)){
                    int time = Integer.parseInt(timeFrame) * 4;
                    for(int i = 0; i < time; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        fromDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,7);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setPlanId(planId);
                        task.setEquipmentId(equipmentId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(fromDate);
//                        task.setExecutor(userId);
                        eqsMaintenanceTasks.add(task);
                    }
                }else if("month".equals(freqUnit)){
                    int time = Integer.parseInt(timeFrame);
                    for(int i = 1; i <= time; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        int fromDate_ = TimeUtils.getMonthOfDate("yyyy-MM-dd",simpleDateFormat.format(fromDate));
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        int day = TimeUtils.getMonthLastDay(Integer.parseInt(TimeUtils.getCurrentTime("yyyy")),fromDate_ + i);
                        Date monthTaskDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,day);
                        fromDate = monthTaskDate;
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
//                        task.setExecutor(userId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(monthTaskDate);
                        eqsMaintenanceTasks.add(task);
                    }
                }else if("half-month".equals(freqUnit)){
                    int count = (int) (Integer.parseInt(timeFrame) /0.5);
                    for(int i = 1; i <= count; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        Date monthTaskDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,15);
                        fromDate = monthTaskDate;
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
//                        task.setExecutor(userId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(monthTaskDate);
                        eqsMaintenanceTasks.add(task);
                    }
                }else if("Season".equals(freqUnit)){
                    int count = Integer.parseInt(timeFrame) /4;
                    for(int i = 1; i < count; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        Date seasonTaskDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,90);
                        fromDate = seasonTaskDate;
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
//                        task.setExecutor(userId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(seasonTaskDate);
                        eqsMaintenanceTasks.add(task);
                    }
                }else if("half-year".equals(freqUnit)){
                    int count = Integer.parseInt(timeFrame) /6;
                    for(int i = 1; i < count; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        Date halfYearTaskDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,180);
                        fromDate = halfYearTaskDate;
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
//                        task.setExecutor(userId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(halfYearTaskDate);
                        eqsMaintenanceTasks.add(task);
                    }
                }else if("year".equals(freqUnit)){
                    int count = Integer.parseInt(timeFrame) /12;
                    for(int i = 1; i < count; i ++){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        Date yearTaskDate = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,360);
                        fromDate = yearTaskDate;
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
//                        task.setExecutor(userId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(yearTaskDate);
                        eqsMaintenanceTasks.add(task);
                    }
                }else{

                }
                eqsMaintenanceTasks.add(firstTask);
            }
        }

        EntityWrapper<EqsMaintenanceTask> maintenanceTaskEntityWrapper = new EntityWrapper<>(EqsMaintenanceTask.class);
        if(ids != null && ids.length > 0){
            maintenanceTaskEntityWrapper.in("planId",ids);
        }
        List<EqsMaintenanceTask> oldTasks = selectList(maintenanceTaskEntityWrapper);
        if(eqsMaintenanceTasks.size() > 0 ){
            if(oldTasks != null && oldTasks.size() > 0){
                oldTasks.forEach(t ->{
                    eqsMaintenanceTasks.removeIf(r -> r.getPlanId().equals(t.getPlanId()) && r.getTaskDate().equals(t.getTaskDate()));
                });
            }
        }

        if(eqsMaintenanceTasks.size() > 0){
            for(EqsMaintenanceTask task : eqsMaintenanceTasks){
                EqsMaintenanceCheck eqsMaintenanceCheck = JSON.parseObject(json, EqsMaintenanceCheck.class);
                eqsMaintenanceCheck.setId("");
                eqsMaintenanceCheck = eqsMaintenanceCheckService.initEqsMaintenanceCheck_(eqsMaintenanceCheck);
                boolean result = eqsMaintenanceCheckService.insert(eqsMaintenanceCheck);
//                if(result){
//                    task.setCheckId(eqsMaintenanceCheck.getId());
//                }
                insert(task);
            }
        }
        return true;
    }

    @Override
    public boolean createMaintenanceTask_(String[] ids,String endTime,String sysConfigCode,String json) {
        EntityWrapper<EqsMaintenancePlan> entityWrapper = new EntityWrapper<>(EqsMaintenancePlan.class);
        if(ids != null && ids.length > 0){
            entityWrapper.in("id",ids);
        }
        List<EqsMaintenancePlan> eqsMaintenancePlans = eqsMaintenancePlanService.selectList(entityWrapper);
        List<EqsMaintenanceTask> eqsMaintenanceTasks = new ArrayList<EqsMaintenanceTask>();
        if(eqsMaintenancePlans != null && eqsMaintenancePlans.size() > 0){
            for(EqsMaintenancePlan plan : eqsMaintenancePlans){
                String freqUnit = plan.getFreqUnit();
                String name = plan.getName();
                String code = plan.getCode();
                String planId = plan.getId();
                String equipmentId = plan.getEquipmentId();
                String maintenanceType = plan.getMaintenanceType();
                Date fromDate = plan.getFromDate();
                Date endDate = TimeUtils.getDateFromTime("yyyy-MM-dd",endTime);
                if(fromDate.getTime() > endDate.getTime()){
                    continue;
                }
                EqsMaintenanceTask firstTask = new EqsMaintenanceTask();
                CodeTable codeTable = new CodeTable();
                codeTable.setCode(sysConfigCode);
                firstTask.setCode(codeTableService.createNewCode(codeTable));
                firstTask.setName(name+code);
                firstTask.setPlanId(planId);
                firstTask.setEquipmentId(equipmentId);
                firstTask.setMaintenanceType(maintenanceType);
                firstTask.setTaskDate(fromDate);
                while (true){
                    Date date = null;
                    if("weekly".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,7);
                    }else if("month".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,30);
                    }else if("half-month".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,15);
                    }else if("Season".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,90);
                    }else if("half-year".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,180);
                    }else if("year".equals(freqUnit)){
                        date = TimeUtils.getTimeDayAfterV3("yyyy-MM-dd",fromDate,360);
                    }
                    fromDate = date;
                    if(date.getTime() <= endDate.getTime()){
                        CodeTable codeTable_ = new CodeTable();
                        codeTable_.setCode(sysConfigCode);
                        String code_ = codeTableService.createNewCode(codeTable_);
                        EqsMaintenanceTask task = new EqsMaintenanceTask();
                        task.setCode(code_);
                        task.setName(name+code);
                        task.setEquipmentId(equipmentId);
                        task.setPlanId(planId);
                        task.setMaintenanceType(maintenanceType);
                        task.setTaskDate(date);
                        eqsMaintenanceTasks.add(task);
                    }else{
                        break;
                    }
                }
                eqsMaintenanceTasks.add(firstTask);
            }
        }

        EntityWrapper<EqsMaintenanceTask> maintenanceTaskEntityWrapper = new EntityWrapper<>(EqsMaintenanceTask.class);
        if(ids != null && ids.length > 0){
            maintenanceTaskEntityWrapper.in("planId",ids);
        }
        List<EqsMaintenanceTask> oldTasks = selectList(maintenanceTaskEntityWrapper);
        if(eqsMaintenanceTasks.size() > 0 ){
            if(oldTasks != null && oldTasks.size() > 0){
                oldTasks.forEach(t ->{
                    eqsMaintenanceTasks.removeIf(r -> r.getPlanId().equals(t.getPlanId()) && r.getTaskDate().equals(t.getTaskDate()));
                });
            }
        }

        if(eqsMaintenanceTasks.size() > 0){
            for(EqsMaintenanceTask task : eqsMaintenanceTasks){
                insert(task);
                EntityWrapper<EqsMaintenancePlanChecktemplate> eqsMaintenancePlanChecktemplateEntityWrapper = new EntityWrapper<>(EqsMaintenancePlanChecktemplate.class);
                eqsMaintenancePlanChecktemplateEntityWrapper.eq("planId",task.getPlanId());
                List<EqsMaintenancePlanChecktemplate> eqsMaintenancePlanChecktemplates = eqsMaintenancePlanCheckTemplateService.selectList(eqsMaintenancePlanChecktemplateEntityWrapper);
                String[] templateIds = null;
                if(eqsMaintenancePlanChecktemplates != null && eqsMaintenancePlanChecktemplates.size() > 0){
                    templateIds = new String[eqsMaintenancePlanChecktemplates.size()];
                    for(int i = 0; i < eqsMaintenancePlanChecktemplates.size(); i ++){
                        templateIds[i] = eqsMaintenancePlanChecktemplates.get(i).getCheckTemplateId();
                    }
                }
                if(templateIds != null){
                    List<EqsMaintenanceCheckTemplate>  eqsMaintenanceCheckTemplateList = eqsMaintenanceCheckTemplateService.getEqsMaintenanceCheckTemplate(templateIds);
                    String val = JSONArray.toJSONString(eqsMaintenanceCheckTemplateList);
                    List<EqsMaintenanceCheck>  list = JSON.parseArray(val,EqsMaintenanceCheck.class);
                    if(list != null && list.size() > 0){
                        for(EqsMaintenanceCheck eqsMaintenanceCheck : list){
                            eqsMaintenanceCheck.setId("");
                            eqsMaintenanceCheck.setTaskId(task.getId());
                            eqsMaintenanceCheckService.insert(eqsMaintenanceCheck);
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateMaintenanceTaskStatus(String status,String[] ids) {
        return baseMapper.updateMaintenanceTaskStatus(status,ids);
    }

    @Override
    public boolean updateMaintenanceTask(EqsMaintenanceTask eqsMaintenanceTask) {
        return baseMapper.updateMaintenanceTask(eqsMaintenanceTask);
    }

    public boolean insertOrUpdate(String json,String json_){
        EqsMaintenanceTask eqsMaintenanceTask = JSON.parseObject(json, EqsMaintenanceTask.class);
        EqsMaintenanceCheck eqsMaintenanceCheck = JSON.parseObject(json_, EqsMaintenanceCheck.class);
        eqsMaintenanceCheck = eqsMaintenanceCheckService.initEqsMaintenanceCheck_(eqsMaintenanceCheck);
        eqsMaintenanceCheckService.insertOrUpdate(eqsMaintenanceCheck);
        return insertOrUpdate(eqsMaintenanceTask);
    }

    @Override
    public List<EqsMaintenanceTask> getByTaskDate(EqsMaintenanceTask eqsMaintenanceTask) {
        return baseMapper.getByTaskDate(eqsMaintenanceTask);
    }

}